<template>
    <div class="e-form">
        <BillTop @cancel="onCancel"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="租赁结算明细" name="zljsDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="服务费用" name="serviceFy" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="退场结算明细" name="tcjsDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="保证金" name="bzj" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="分包商分摊成本" name="fbsftcb" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%;" class="form">
                            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="240px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算编号" prop="billNo">{{ formData.billNo }}</el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="机构" prop="orgName">
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="业务类型" prop="businessTypeValue">
                                            <el-select
                                                v-model="formData.businessTypeValue"
                                                placeholder="请选择"
                                                @change="onSelectBusinessTypeKey"
                                            >
                                                <el-option
                                                    v-for="item in turnoverData.businessTypeArr.slice(3, 6)"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="源单编号" prop="sourceNo">
                                            <span style="color: #999;" v-if="!formData.sourceNo">请选择源单</span>
                                            <template v-else>
                                                <span>{{ formData.sourceNo }}</span>
                                                <span class="a" @click="viewYuanDan(formData.sourceId)">查看</span>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算单位" prop="settlementUnitId">
                                            <div style="display: flex; width: 100%;">
                                                <el-input
                                                    style="flex: 1;"
                                                    placeholder="请选择结算明细"
                                                    v-model="formData.settlementUnitName"
                                                >
                                                    <i slot="suffix" class="el-icon-document-copy" @click="onSelectMaterial"></i>
                                                </el-input>
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="结算类型" prop="settlementType">{{setSettleType}}</el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="发票号" prop="invoiceNo">
                                            <el-input
                                                style="flex: 1;"
                                                placeholder="请输入发票号"
                                                v-model="formData.invoiceNo"
                                                v-enterInteger1
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人员" prop="entryPersonnelId">{{ formData.entryPersonnelName }}</el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="不含税金额(元)" prop="taxExcluding">{{ formData.taxExcluding }}</el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="结算日期" prop="settlementDate">
                                            <el-date-picker
                                                v-model="formData.settlementDate"
                                                type="date"
                                                value-format="yyyy-MM-dd"
                                                placeholder="请选择结算日期"
                                            ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税率%" prop="taxRate">
                                             <el-input
                                                type="number"
                                                placeholder="请输入税率"
                                                v-model="formData.taxRate"
                                                @change="changeTaxRateEvent"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税价合计" prop="totalAmount">
                                            <span v-if="formData.sourceNo">{{ formData.totalAmount }}</span>
                                            <span v-else style="color: #999;">{{ '请选择源单编号' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税额" prop="taxAmount">
                                            <el-input
                                                style="flex: 1;"
                                                placeholder="请输入税额"
                                                v-model="formData.taxAmount"
                                                @change="taxAmountEvent"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="服务单位费用(含税，元)" prop="totalFreight">
                                            <span> {{ TotalSettlementAmountService }} </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="进场费(元)" prop="slottingFee">
                                            <el-input
                                                style="flex: 1;"
                                                placeholder="请输入进场费"
                                                v-model="formData.slottingFee"
                                                @change="slottingFeeEvent"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="赔偿费" prop="damages">
                                            <span> {{ formData.damages }} </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="退场">
                                            <el-checkbox v-model="formData.isExit"
                                            @change="isExitEvent"
                                            ></el-checkbox>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="退场费" prop="exitFees">
                                            <el-input
                                                style="flex: 1;"
                                                placeholder="请输入退场费"
                                                v-model="formData.exitFees"
                                                @change="exitFeesEvent"
                                                :disabled='!formData.isExit'
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="冲预付款金额(元)"
                                        prop="offsetAdvancePayment">
                                            <el-checkbox v-model="formData.isOffsetAdvancePayment"
                                            @change="isAdvanceChargeAmount"
                                            ></el-checkbox>&nbsp;
                                            <el-input v-if="formData.isOffsetAdvancePayment&&!formData.isFinalSettlement"
                                                style="flex: 1;"
                                                placeholder="请输入冲预付款金额"
                                                v-model.number="formData.offsetAdvancePayment"
                                                @change="offsetAdvancePaymentEvent"
                                            ></el-input>
                                            <span v-if="formData.isOffsetAdvancePayment&&formData.isFinalSettlement">
                                                {{formData.offsetAdvancePayment}}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="累计结算金额" prop="cumulativeSettlementAmount">
                                            {{ setTotalSettlementAmount }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="冲个人借支" prop="isPersonalBorrowing">
                                            <el-checkbox v-model="formData.isPersonalBorrowing"
                                            @change="borrowingEvent"
                                            :disabled='formData.businessTypeKey != 5'
                                            ></el-checkbox>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="终期结算" prop="isFinalSettlement">
                                            <el-checkbox v-model="formData.isFinalSettlement"
                                            @change="isFinalSettlementEvent"
                                            ></el-checkbox>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="冲销对象：" >
                                            <!-- 下拉框 -->
                                            <el-select
                                                v-model="formData.reversalObjectName"
                                                placeholder="请选择"
                                                @change="changeReversalObject"
                                                :disabled="!formData.isPersonalBorrowing"
                                            >
                                                <el-option
                                                    v-for="item in reversalObjectList"
                                                    :key="item.reversalObjectId"
                                                    :label="item.reversalObjectName"
                                                    :value="item.reversalObjectId"
                                                    >
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="借支人员" prop="borrowerId">
                                            <div style="display: flex; width: 100%;">
                                                <el-input
                                                    style="flex: 1;"
                                                    placeholder="请选择借支人员"
                                                    v-model="formData.borrowerName"
                                                    :disabled="!formData.isPersonalBorrowing"
                                                >
                                                    <i slot="suffix" class="el-icon-document-copy"
                                                    v-if="formData.isPersonalBorrowing"
                                                    @click="onGetSigningName"></i>
                                                </el-input>
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="冲个人借支金额(元)" prop="personalBorrowing">
                                            <el-input
                                                style="flex: 1;"
                                                placeholder="请输入冲个人借支金额"
                                                v-model="formData.personalBorrowing"
                                                :disabled="!formData.isPersonalBorrowing"
                                                @change="personalBorrowingEvent"
                                                type="number"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态" prop="state">
                                            {{ getState(formData.state) }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="传输财务共享" prop="isSharing">
                                            <span> {{ !formData.isSharing ? '未传' : '已传' }} </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种" >
                                            {{ formData.currency }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币" prop="baseCurId">
                                            <span> {{ formData.baseCurName }} </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="结算金额(本位币)" prop="baseSettleAmount">
                                            {{ formData.baseSettleAmount }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率" prop="rmbRate">
                                            <span> {{ formData.rmbRate }} </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="本位币汇率" prop="baseCurRate">
                                            {{ formData.baseCurRate }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注" prop="remarks">
                                            <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="请输入内容"
                                                v-model="formData.remarks"
                                                maxlength='500'
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="zljsDetailCon" class="con">
                        <div class="tabs-title" id="zljsDetail">租赁结算明细</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onSelectMaterial">选择物资</el-button>
                                    </div>
                                </div>
                            </div>
                        <div class="errMessageBox">
                                <p class="errMessage" v-for="(item,index) in errorParmesList" :key='index'>
                                    {{item}}
                                </p>
                        </div>
                            <div class="e-tree-table">
                                <div class="errorMsg" v-if="errorMsg.length>0">
                                    <span >
                                        {{ errorMsg.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    ref="detailsListTable"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="uuid"
                                    :data="detailsList"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    default-expand-all
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': detailsList, '_this': this, 'ref': 'detailsListTable' }"
                                >
                                    <el-table-column prop="itemName" label="操作" width="100" fixed>
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;" v-if='!row.children'>
                                                <img src="@/assets/btn/delete.png" class="cancel_delete" title="删除" @click="deleteEle(row)">
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="materialClassName" label="物资类别" width="200" show-overflow-tooltip>
                                        <template slot-scope="{ row }">
                                          {{row.materialClassName}}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="materialName" label="物资名称" min-width="220"></el-table-column>
                                    <el-table-column prop="spec" align="right" label="规格" width="200"></el-table-column>
                                    <el-table-column prop="texture" align="right" label="材质" width="200"></el-table-column>
                                    <el-table-column prop="unit" align="right" label="单位" width="200"></el-table-column>
                                    <el-table-column prop="unsettledQuantity" align="right" label="未结算数量" width="200"></el-table-column>
                                    <el-table-column prop="settledQuantity" align="right" label="结算数量" width="200">
                                        <template slot-scope="{ row }">
                                            <el-input v-if='!row.children' v-model="row.settledQuantity" @change="settledQuantityEvent(row)"
                                            v-enterFloat2Neg="{
                                                set: row,
                                                key:'settledQuantity'
                                            }"
                                            ></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="timingUnit" align="right" label="计时单位" width="200"></el-table-column>
                                    <el-table-column prop="startTime" align="right" label="结算开始时间" width="200">
                                        <template slot-scope="{ row }" v-if='!row.children'>
                                            <el-date-picker
                                                v-model="row.startTime"
                                                type="date"
                                                value-format="yyyy-MM-dd"
                                                placeholder="请选择开始时间"
                                            ></el-date-picker>
                                        </template >
                                    </el-table-column>
                                    <el-table-column prop="endTime" align="right" label="结算结束时间" width="200">
                                            <template slot-scope="{ row }" v-if='!row.children'>
                                            <el-date-picker
                                                v-model="row.endTime"
                                                type="date"
                                                value-format="yyyy-MM-dd"
                                                placeholder="请选择结束时间"
                                            ></el-date-picker>
                                        </template >
                                    </el-table-column>
                                    <el-table-column prop="leasePrice" align="right" label="租赁单价(元)" width="200"></el-table-column>
                                    <el-table-column prop="leaseTime" align="right" label="租赁时间" width="200">
                                        <!-- <template slot-scope="{ row }">
                                            {{  row.leaseTime }}
                                        </template> -->
                                    </el-table-column>
                                    <el-table-column prop="leaseAmount" align="right" label="租赁金额(元)" width="200">
                                        <template slot-scope="{ row }">
                                            <el-input v-if='!row.children' v-model="row.leaseAmount"   v-enterFloatNeg="{
                                                set: row,
                                                key: 'leaseAmount'
                                            }"
                                            @change="onChangeAmount(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="serviceFyCon" class="con">
                        <div class="tabs-title" id="serviceFy">服务费用</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onAddList1">新增行</el-button>
                                    </div>
                                </div>
                                 <div class="right">
                                    合计：{{TotalSettlementAmountService}}
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <div class="errorMsg" v-if="errorMsg.length>0">
                                    <span >
                                        {{ errorMsg.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    ref="tableDataServiceShowTable"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="id"
                                    :data="tableDataServiceShow"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataServiceShow, '_this': this, 'ref': 'tableDataServiceShowTable' }"
                                >
                                    <el-table-column type="selection" fixed width="55"> </el-table-column>
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleService(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="合同编号" min-width="200" prop="contractNumber" show-overflow-tooltip>
                                        <template slot-scope="{ row, $index }">
                                            {{ row.contractNumber }}<i slot="suffix" class="el-icon-document-copy"
                                            style="margin: 0 0 0 5px;" @click="onSelectHetong($index)"></i>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="结算单位" min-width="200" prop="settlementUnitName" show-overflow-tooltip>
                                        <template slot-scope="{ row }">
                                            {{ row.settlementUnitName }}<i slot="suffix" class="el-icon-document-copy"
                                            style="margin: 0 0 0 5px;" @click="onSelectJsUnit(row)"></i>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="发票编号" width="200" prop="invoiceNo" show-overflow-tooltip>
                                    <template v-slot="{ row }">
                                        <el-input
                                            v-model="row.invoiceNo"
                                            v-enterInteger1
                                            @blur="invoiceNoBlur(row)"
                                        ></el-input>
                                    </template>
                                    </el-table-column>
                                     <el-table-column label="清单名称" width="150" prop="contractDtlName" show-overflow-tooltip>
                                        <template slot-scope="{ row }">
                                            <el-input v-model="row.contractDtlName"
                                              @blur="detailedListNameBlur"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数量" width="150" prop="quantity">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.quantity"
                                            @change="quantityBlur(row)"
                                            ></el-input>
                                        </template>
                                    </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价(元)"
                                    width="100"
                                >
                                </el-table-column>
                                    <el-table-column label="金额(元)" width="150" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.amount" @change="amountBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税率%" width="150" prop="taxRate">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.taxRate" @change="taxRateBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税额(元)" width="150" prop="taxAmount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat2 v-model="row.taxAmount"
                                            @change="taxAmountBlur(row)"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="税价合计(元)" width="150" prop="totalAmount"></el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="tcjsDetailCon" class="con">
                                            <!-- {{webData}} -->
                        <div class="tabs-title" id="tcjsDetail">退场结算明细</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onSelectExitDetail">选择物资</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <div class="errorMsg" v-if="errorMsg.length>0">
                                    <span >
                                        {{ errorMsg.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    ref="tableDataExitTable"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="uuid"
                                    :data="tableDataExit"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :default-expand-all='true'
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataExit, '_this': this, 'ref': 'tableDataExitTable' }"
                                >
                                    <el-table-column prop="itemName" label="操作" width="150">
                                        <template slot-scope="{ row }">
                                            <div class="handle">
                                                <div style="cursor: pointer;"
                                                v-if='!row.children'
                                                >
                                                    <img src="@/assets/btn/delete.png"  @click="deleteExit(row)">
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="物资类别" width="200" prop="materialClassName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="物资名称" width="200" prop="materialName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="规格" width="150" prop="spec"></el-table-column>
                                    <el-table-column label="材质" width="150" prop="texture"></el-table-column>
                                    <el-table-column label="单位" width="150" prop="unit"></el-table-column>
                                    <el-table-column label="入库数量" width="150" prop="receiptQuantity"></el-table-column>
                                    <el-table-column label="本次退场数量" width="150" prop="exitsQuantity"></el-table-column>
                                    <el-table-column label="截止上期末退场数量" width="200" prop="exitsQuantitySqm"></el-table-column>
                                    <el-table-column label="截止本期末退场数量" width="200" prop="exitsQuantityBqm"></el-table-column>
                                    <el-table-column label="退场时间" width="150" prop="exitsTime"></el-table-column>
                                    <el-table-column label="损耗原因" width="150" prop="reason"></el-table-column>
                                    <el-table-column label="赔偿数量" width="150" prop="compensateQuantity"></el-table-column>
                                    <el-table-column label="赔偿费(元)" width="150" prop="damages">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat v-model="row.damages"  v-if='!row.children'></el-input>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="bzjCon" class="con">
                        <div class="tabs-title" id="bzj">保证金</div>
                        <div class="e-table">
                            <div class="mainTitle"><i class="el-icon-d-arrow-right"></i>暂扣保证金</div>
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onAddListZk">添加</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <el-table
                                    ref="tableDataBzjShow1Table"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="id"
                                    :data="tableDataBzjShow1"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataBzjShow1, '_this': this, 'ref': 'tableDataBzjShow1Table' }"
                                >
                                    <el-table-column type="selection" fixed width="55"> </el-table-column>
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleBzj(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="名称" min-width="200" prop="returnDepositName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="暂扣保证金(元)" width="200" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat v-model.number="row.amount"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="截止上期末暂扣保证金(元)" width="250" prop="amountBqm" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="截止本期末暂扣还保证金(元)" width="250" prop="amountSqm">
                                        <template slot-scope="{ row }">
                                            {{ row.amount*1 + ((row.amountBqm*1)||0) }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="说明" min-width="150" prop="remarks"></el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="e-table">
                            <div class="mainTitle"><i class="el-icon-d-arrow-right"></i>返还保证金</div>
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" :disabled="!formData.sourceId" @click="onAddListFh">添加</el-button>
                                        <span v-if="!formData.sourceId" style="color: #999;">{{ '请选择源单编号' }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <el-table
                                    ref="tableDataBzjShow2Table"
                                    key="tableRef"
                                    border
                                    style="width: 100%"
                                    row-key="dtlId"
                                    :data="tableDataBzjShow2"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataBzjShow2, '_this': this, 'ref': 'tableDataBzjShow2Table' }"
                                >
                                    <el-table-column type="selection" fixed width="55"> </el-table-column>
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column prop="itemName" label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleBzj(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="名称" min-width="200" prop="returnDepositName" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="截止上期末未返还保证金(元)" width="250" prop="amountBqm" show-overflow-tooltip> </el-table-column>
                                    <el-table-column label="返还保证金(元)" width="200" prop="amount">
                                        <template slot-scope="{ row }">
                                            <el-input v-enterFloat v-model="row.amount"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="截止本期末未返还保证金(元)" width="250" prop="amountSqm">
                                        <template slot-scope="{ row }">
                                            {{ row.amountBqm - row.amount }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="说明" min-width="150" prop="remarks"></el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="fbsftcbCon" class="con">
                        <div class="tabs-title" id="fbsftcb">分包商分摊成本</div>
                        <div class="e-table" style="background-color: #fff">
                            <div class="top">
                                <div class="left">
                                    <div class="select_box">
                                        <el-button class="btn-greenYellow" @click="onSelectFbsftcb">选择分包商</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="e-tree-table">
                                <div class="errorMsg2" v-if="errorMsg2.length>0">
                                    <span >
                                        {{ errorMsg2.join(',') }}
                                    </span>
                                </div>
                                <el-table
                                    border
                                    style="width: 100%"
                                    row-key="id"
                                    ref="tableDataFbsftcbShowTable"
                                    :data="tableDataFbsftcbShow"
                                    :cell-class-name="cellClsNm"
                                    @cell-mouse-enter="cellMouseEnter"
                                    @cell-mouse-leave="cellMouseLeave"
                                    class="table"
                                    :max-height="$store.state.tableHeight"
                                    v-sortTable="{ 'tableData': tableDataFbsftcbShow, '_this': this, 'ref': 'tableDataFbsftcbShowTable' }"
                                >
                                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                                    <el-table-column label="操作" width="150" v-if="formData.isSystemGeneration !== 1">
                                        <template slot-scope="{ row }">
                                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                                <i
                                                    class="el-icon-delete"
                                                    style="cursor: pointer; font-size: 20px"
                                                    :class="{
                                                        'icon-delete-active-color': MouseEnterId == row.dtlId
                                                    }"
                                                    @click="deleteEleFbsftcb(row)"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="subcontractorName" label="分包商名称" width="150"></el-table-column>
                                    <el-table-column prop="subcontractName" label="合同名称" min-width="220"></el-table-column>
                                    <el-table-column prop="subcontractNumber" align="right" label="合同编号" width="200"></el-table-column>
                                    <el-table-column prop="planAmount" align="right" label="设计金额" width="200"></el-table-column>
                                    <el-table-column prop="apportionmentRatio" align="right" label="分摊比例%" width="200"></el-table-column>
                                    <el-table-column prop="apportionmentAmount" align="right" label="分摊金额(元)" width="200">
                                        <template slot-scope="{ row }">
                                             <el-input type="number" v-model="row.apportionmentAmount" @change="apportionmentAmountEvent">
                                             </el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="providType" align="right" label="甲供类型" width="200">
                                        <template slot-scope="{ row }">
                                            <!-- contractType 合同类型 1 分包合同 2 加工合同 3 物资销售合同 -->
                                            <!-- 1、当选择分包合同和加工合同时，甲供类型下拉单选：工程消耗，安全环保支出，研发支出 -->
                                            <!-- 2、当选择的合同是销售合同时：为销售消耗，不可修改。 -->
                                            <el-select v-if="row.contractType !== 3"
                                                v-model="row.providType"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in ctClassify.supplyTypeList"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                ></el-option>
                                            </el-select>
                                            {{ row.contractType === 3 ? '销售消耗' : '' }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="consumeType" align="right" label="消耗类型" width="200">
                                        <template slot-scope="{ row }">
                                            <!-- 分包合同：系统计算匹配：甲供、超甲供扣款，非甲供扣款。加工合同：可为空。 -->
                                            <!-- 2、当选择的合同是销售合同时：为销售消耗，不可修改。 -->
                                            <el-select v-if="row.contractType !== 3"
                                                v-model="row.consumeType"
                                                placeholder="请选择"
                                            >
                                                <el-option
                                                    v-for="item in turnoverData.consumeTypeArr"
                                                    :key="item.id"
                                                    :label="item.name"
                                                    :value="item.id"
                                                ></el-option>
                                            </el-select>
                                            {{ row.contractType === 3 ? '销售消耗' : '' }}
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="billId" bucketName="turnoverLeaseDisburse" />
                    </div>
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory :billType="Number(billType)" @getAuditHistory="getAuditHistory" :tableData="auditHistoryData" ref="ComExaHistory" />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <!-- isSystemGeneration 是否系统生成(1:是 0:否) -->
            <ComExaButtons :auditState="auditState" @exas="exas" :canDelete="formData.isSystemGeneration !== 1" :founderId="formData.founderId" :state="formData.state"/>
            <el-button @click="onCancel">取消</el-button>
        </div>
    </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { openAppClient, selectDataClient, throttle, formatDate, getUuid, treeToList } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { delLeaseDisburseBase, getLeaseDisburseBase, getLeaseDisburseDetailLs, getLeaseDisburseServiceLs, getLeaseDisburseZltcLs, getLeaseDisburseBzjLs, getLeaseDisburseFtcbLs, modifyLeaseDisburseBase, modifyLeaseDisburseDetailLs, modifyLeaseDisburseServiceLs, modifyLeaseDisburseZltcLs, modifyLeaseDisburseBzjLs, modifyLeaseDisburseFtcbLs, getAuditHistoryLs, getCurrentState, flowCommit, flowUndoAudit, flownullify, getReversalObject, getPrevAmount, getAdvancePayment, checkIsChange
} from '@/api/settlementManagement/weeklyMaterialSettlement/leaseDisburse'
import AttachComp from '@/components/common/attachIndex'
//审核历史
import ComExaHistory from '@/components/common/exaHistory'
import ComExaButtons from '@/components/common/exaButtons'
import { mapState, mapMutations } from 'vuex'
// eslint-disable-next-line no-unused-vars
import { uidBuilder } from '@/api/base/uid'
import '@/utils/jquery.scrollTo.min'

let oldRouter = {} // 上一个页面来源
export default {
    components: {
        AttachComp,
        ComExaHistory,
        ComExaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: 6096,
            flowParams: {
                'billId': '',
                'billType': '',
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            //表单数据
            formData: {},
            //冲销对象选选择
            reversalObjectList: [],
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            auditHistoryData: [],
            auditState: {},
            rules: {
                businessTypeKey: [{ required: true, message: '请选择业务类型', trigger: ['blur', 'change'] }],
                settlementUnitId: [{ required: true, message: '请选择结算单位', trigger: 'blur' }],
                settlementDate: [{ required: true, message: '请选择结算日期', trigger: ['blur', 'change'] }],
                slottingFee: [{ required: true, message: '请输入进场费', trigger: ['blur', 'change'] }],
                exitFees: [{ required: true, message: '请输入退场费', trigger: ['blur', 'change'] }],
                offsetAdvancePayment: [{ validator: (rule, value, callback) => {
                    console.log('offsetAdvancePayment rule: ', rule)
                    if (!this.formData.isOffsetAdvancePayment) {
                        callback()
                    } else if(value !== 0 && !value) {
                        callback(new Error('请输入冲预付款金额'))
                    } else {
                        callback()
                    }
                }, trigger: ['blur', 'change'] }],
            },
            MouseEnterId: 0,
            detailsList: [
                {
                    'children': [],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': '4521wzxzx8sdwzxwx5z4c54c5x'
                }
            ], // 租赁结算明细（重写）
            mapObj: {}, // 缓存租赁结算明细数据
            mapObjExit: {}, // 缓存退场结算明细数据
            tableDataService: [], // 服务费用明细
            tableDataExit: [
                {
                    'children': [],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': 'wqe54z5xz612sd155zxasf'
                }
            ], // 退场结算明细
            tableDataBzj: [], // 保证金
            tableDataFbsftcb: [], // 分包商分摊成本
            errorMsg: [],
            errorMsg2: [],
            errorList: [], // 控制导航栏感叹号的显示
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            jsdwData: {
                businessUnitTypes: [],
                keyword: '',
                limit: 10,
                orgId: '',
                outerTypes: [],
                page: 1,
                states: [],
                type: [0, 1, 2, 3],
                supplierTypes: [],
                subcontractorTypes: [],
                businessTypes: [],
            },
            //结算明细错误提示数组
            errorParmesList: [],
            tabArr: [], //用于验证功能列表中的必填项
            previousTotalAmount: 0, //上期末金额
            noAdvanceCharge: 0, //未冲销预付款
            webData: ''
        }
    },
    computed: {
        ...mapState('equip', ['equipData']),
        ...mapState('contract', ['ctClassify']), // 甲供类型
        ...mapState('turnover', ['turnoverData']), // 业务类型、消耗类型
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 85 - this.lastConHeight
        },
        billId () {
            return this.$route.query.billid
        },
        tableDataServiceShow () {
            return this.tableDataService.filter(item => item.changeType !== -1)
        },
        tableDataBzjShow1 () {
            return this.tableDataBzj.filter(item => item.changeType !== -1 && item.depositType === 1)
        },
        tableDataBzjShow2 () {
            return this.tableDataBzj.filter(item => item.changeType !== -1 && item.depositType === 2)
        },
        tableDataFbsftcbShow () {
            return this.tableDataFbsftcb.filter(item => item.changeType !== -1)
        },
        //基本信息累计结算金额
        setTotalSettlementAmount () {
            const target = (Number(this.formData.totalAmount) || 0) + (Number(this.previousTotalAmount) || 0)
            return target.toFixed(2) * 1
        },
        //服务费用税价合计总和
        TotalSettlementAmountService () {
            return this.tableDataServiceShow.reduce((a, b)=>a + (Number(b.totalAmount) || 0), 0)
        },
        //当前结算类型
        setSettleType () {
            const obj = {
                1: '内部列账',
                2: '外来发票',
            }
            return obj[this.formData.settlementType]
        },
    },
    watch: {
        //租赁结算明细税额汇总
        detailsList: {
            deep: true,
            handler (newVal) {
                if(newVal.length > 0) {
                    const total = newVal[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
                    //计算税额
                    this.formData.taxAmount = ((this.formData.taxRate || 0) * total / 100).toFixed(2) * 1
                    //计算不含税金额
                    this.formData.taxExcluding = (total + (Number(this.formData.damages) || 0) + (Number(this.formData.slottingFee) || 0) + (Number(this.formData.exitFees) || 0)).toFixed(2) * 1
                    //更新税价合计
                    this.formData.totalAmount = ((Number(this.formData.taxExcluding) || 0) + (Number(this.formData.taxAmount) || 0)).toFixed(2) * 1
                }
            }
        },
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //获取未冲销预付款
        'formData.sourceId': {
            deep: true,
            async handler (newVal) {
                console.log(newVal, 'newVal')
                if(newVal) {
                    const data = await getAdvancePayment({ contractId: newVal })
                    if(typeof data == 'object') {
                        if(data.code == 200) {
                            this.noAdvanceCharge = data ? (data.data || 0) : 0
                        }else {
                            this.noAdvanceCharge = 0
                        }
                    }else {
                        this.noAdvanceCharge = data || 0
                    }
                }

            }
        },
        //监听服务明细表格及时更新冲销对象
        tableDataServiceShow: {
            deep: true,
            handler (newVal) {
                if(newVal && newVal.length > 0) {
                    //获取单位id和名称
                    const targetId = []
                    newVal.forEach(item=>{
                        if(item.reversalObjectId) {
                            const obj = {
                                reversalObjectId: item.settlementUnitId,
                                reversalObjectName: item.settlementUnitName
                            }
                            targetId.push(obj)
                        }
                    })
                    //合并目标并去重
                    const list = [...this.reversalObjectList, ...targetId]
                    this.reversalObjectList = this.duplicateRemoval(list)
                }
            }
        }
    },
    created () {
        this.flowParams.billId = this.$route.query.billid
        this.flowParams.billType = this.billType
    },
    mounted () {
        // 设置滚动事件
        this.registScroll()
        this.getData()
        this.auditState = this.$route.params.auditState
        if (!this.auditState) {
            this.getCurrentUnitInfo()
        }
        // 如果是新增保存后点击“继续”跳转过来的，则定位到第2个tab
        if (oldRouter.path === '/turnoverLeaseDisburseAdd') {
            this.tabsName = 'zljsDetail'
            this.$nextTick(() => {
                this.onChangeTab({ name: 'zljsDetail' })
            })
        }
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'zljsDetail', 'serviceFy', 'tcjsDetail', 'bzj', 'fbsftcb', 'attach', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //去重
        duplicateRemoval (list) {
            if(list && list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                    for (let j = i + 1; j < list.length; j++) {
                        if(list[i].reversalObjectId == list[j].reversalObjectId) {
                            list.splice(j, 1)
                            j--
                        }
                    }
                }
            }
            return list
        },
        //获取数据
        async getData () {
            // 获取基础信息
            const formData = await getLeaseDisburseBase({ billId: this.billId })
            formData.businessTypeKey = String(formData.businessTypeKey)
            this.formData = formData
            //获取清单截止上期末累计结算金额
            getPrevAmount({ sourceId: formData.sourceId })
                .then(res=>{
                    if(typeof res == 'number') {
                        this.previousTotalAmount = res
                    }else {
                        this.previousTotalAmount = 0
                    }
                })
            // 获取租赁结算明细 (返回数据为树结构)
            const tableData = await getLeaseDisburseDetailLs({ billId: this.billId })
            // 结算明细设置表格row-key
            if(tableData.length > 0) {
                tableData[0].children.forEach(item=>{
                    item.uuid = getUuid()
                })
                tableData[0].uuid = getUuid()
                this.detailsList = tableData
            }
            // 获取服务费用明细
            this.tableDataService = await getLeaseDisburseServiceLs({ billId: this.billId })
            // 获取退场结算明细 (返回数据为树结构)
            const tableDataExit = await getLeaseDisburseZltcLs({ billId: this.billId })
            if(tableDataExit.length > 0) {
                tableDataExit[0].children.forEach(item=>{
                    item.uuid = getUuid()
                })
                tableDataExit[0].uuid = getUuid()
                this.tableDataExit = tableDataExit
            }
            // 获取保证金
            const tableDataBzj = await getLeaseDisburseBzjLs({ billId: this.billId })
            tableDataBzj.forEach(item => {
                item.id = item.dtlId
            })
            this.tableDataBzj = tableDataBzj
            // 获取分包商分摊成本
            this.tableDataFbsftcb = await getLeaseDisburseFtcbLs({ billId: this.billId })
            // 获取冲销对象
            const objRes = await getReversalObject({ billId: this.billId })
            if(objRes.length && objRes[0] != null && objRes[0].reversalObjectId != '' ) {
                this.reversalObjectList = objRes
            }
        },
        async getCurrentUnitInfo () {
            this.auditState = await getCurrentState(this.flowParams)
        },
        //冲个人借支金额事件
        personalBorrowingEvent (val) {
            if(val) {
                //判断是否大于税价合计
                if(Number(val) > this.formData.totalAmount) {
                    this.formData.personalBorrowing = 0
                    this.$message.error('冲个人借支不可大于税价合计')
                }else {
                    this.formData.personalBorrowing = Number(val)
                }
            }else {
                this.formData.personalBorrowing = 0
            }
        },
        //冲个人借支事件
        borrowingEvent (val) {
            if(val) {
                this.clientPop(
                    'info',
                    '确认冲个人借支？',
                    () => {
                        this.formData.isPersonalBorrowing = true
                    },
                    null,
                    ()=>{
                        this.formData.isPersonalBorrowing = false
                        this.formData.reversalObjectName = ''
                        this.formData.reversalObjectId = ''
                        this.formData.borrowerName = ''
                        this.formData.personalBorrowing = 0
                    }
                )
            }else {
                this.formData.isPersonalBorrowing = false
                this.formData.reversalObjectName = ''
                this.formData.reversalObjectId = ''
                this.formData.borrowerName = ''
                this.formData.personalBorrowing = 0
            }
        },
        //是否勾选预付款事件
        isAdvanceChargeAmount (val) {
            if(val) {
                //剩余未冲销预付款如果为0则禁用冲预付款功能
                const isNo = this.noAdvanceCharge == 0
                this.formData.isOffsetAdvancePayment = isNo ? false : true
                if(isNo) {
                    this.$message.warning('未冲销预付款金额为0不需要进行冲预付款操作')
                    return
                }
                this.formData.offsetAdvancePayment = this.noAdvanceCharge
            }else {
                this.formData.offsetAdvancePayment = 0
            }
        },
        //预付款金额事件
        offsetAdvancePaymentEvent (val) {
            //修改的值必须大于0小于等于未冲销预付款金额
            if(val <= 0 || val > this.noAdvanceCharge) {
                this.formData.offsetAdvancePayment = this.noAdvanceCharge
                this.$message.error('冲预付款金额必须大于0并且小于等于未冲销预付款金额')
            }
        },
        //终期结算事件
        isFinalSettlementEvent (val) {
            if(val) {
                this.clientPop(
                    'info',
                    '是否终期结算，终期结算后不能再对结算单位进行结算',
                    //确定
                    ()=>{
                        //终期结算时需要将所有预付款进行结算
                        this.formData.isOffsetAdvancePayment = true
                        this.formData.offsetAdvancePayment = this.noAdvanceCharge || 0
                    },
                    null,
                    //取消
                    ()=>{
                        this.formData.isOffsetAdvancePayment = false
                        this.formData.offsetAdvancePayment = 0
                        this.formData.isFinalSettlement = false
                    }
                )
            }else {
                this.formData.isOffsetAdvancePayment = false
                this.formData.offsetAdvancePayment = 0
            }
        },
        //是否勾选退场事件
        isExitEvent (val) {
            if(!val) {
                this.formData.exitFees = 0
                //计算不含税金额
                const total = this.detailsList[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
                this.formData.taxExcluding = total + (Number(this.formData.damages) || 0) + (Number(this.formData.slottingFee) || 0) + (Number(this.formData.exitFees) || 0)
                //计算税价合计
                this.formData.totalAmount = (Number(this.formData.taxExcluding) || 0) +
            (Number(this.formData.taxAmount ) || 0)
            }
        },
        //税率事件
        changeTaxRateEvent (val) {
            let res = 0
            if(val <= 100 && val >= 0) {
                res = val
            }else {
                this.$message.error('税率的有效值应为0~100')
            }
            //计算税额
            this.formData.taxRate = Number(res).toFixed(2) * 1
            if(this.detailsList[0].children.length > 0) {
                const total = this.detailsList[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
                this.formData.taxAmount = ((this.formData.taxRate || 0) * total / 100).toFixed(2) * 1
            }
            //计算税价合计
            this.formData.totalAmount = (Number(this.formData.taxExcluding) || 0) +
            (Number(this.formData.taxAmount) || 0)
        },
        //税额事件
        taxAmountEvent (val) {
            //计算税价合计
            this.formData.totalAmount = (Number(this.formData.taxExcluding) || 0) +
            (Number(val) || 0)
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await getAuditHistoryLs(this.flowParams)
        },
        //验证租赁结算明细
        verificationSettlementDetails () {
            const nan = NaN
            const err = []
            if(!this.detailsList[0].children.length) {
                err.push('请选择结算明细')
                return err
            }
            //验证本期结算数量
            this.detailsList[0].children.some(item=>{
                if(item.settledQuantity === '' || item.settledQuantity == nan || item.settledQuantity <= 0) {
                    err.push('结算数量不能为空且必须大于0')
                    return true
                }
            })
            //验证结算开始时间
            this.detailsList[0].children.some(item=>{
                if(item.startTime === '' || item.startTime == nan) {
                    err.push('结算开始时间不能为空')
                    return true
                }
            })
            //验证结算结束时间
            this.detailsList[0].children.some(item=>{
                if(item.endTime === '' || item.endTime == nan) {
                    err.push('结算结束时间不能为空')
                    return true
                }
            })
            //验证租赁金额
            this.detailsList[0].children.some(item=>{
                if(item.leaseAmount === '' || item.leaseAmount == nan) {
                    err.push('租赁金额不能为空')
                    return true
                }
            })
            //验证本期结算数量是否超未结算数量
            this.detailsList[0].children.some(item=>{
                if(item.settledQuantity > item.unsettledQuantity) {
                    err.push('结算数量不能超过未结算数量')
                    return true
                }
            })
            //验证租赁金额是否大于0
            this.detailsList[0].children.some(item=>{
                if(item.leaseAmount <= 0) {
                    err.push('租赁金额必须大于0')
                    return true
                }
            })
            return err
        },
        // 保存
        async saveFn (str, temp) {
            temp
            // if(temp) {
            //     this.errorParmesList = []
            //     const errList = this.verificationSettlementDetails()
            //     if(errList.length > 0) {
            //         this.errorParmesList = errList
            //         return
            //     }
            //     const tableData = []
            //     const promiseArr = []
            //     treeToList(this.tableData).forEach(item => {
            //         if (item.parentId === '0') {
            //             // 租赁时间 金额/数量*租赁单价
            //             item.children.forEach(subItem => {
            //                 subItem.leaseTime = subItem.parentId === '0' ? '' : (subItem.settledQuantity ? Math.round(subItem.leaseAmount / subItem.settledQuantity * subItem.leasePrice * 10) / 10 : 0)
            //             })
            //             const obj = {
            //                 children: item.children,
            //                 topClassId: item.materialClassId,
            //                 topClassName: item.materialClassName,
            //                 totalAmount: item.children.reduce((result, prev) => {
            //                     return result + prev.leaseAmount
            //                 }, 0),
            //                 totalQuantity: item.children.reduce((result, prev) => {
            //                     return result + prev.settledQuantity
            //                 }, 0)
            //             }
            //             tableData.push(obj)
            //         }
            //     })
            //     promiseArr.push(modifyLeaseDisburseDetailLs(tableData))
            //     await Promise.all(promiseArr)
            //     if (str !== 'commit') {
            //         this.clientPop('suc', '保存成功', () => {
            //         })
            //     } else {
            //         await flowCommit(this.flowParams)
            //         this.clientPop('suc', '操作成功', () => {
            //             this.$router.replace('/turnoverLeaseDisburse')
            //         })
            //     }
            //     return
            // }
            //--------------------------------------------------------------
            this.errorList = []
            const promiseArr = []
            promiseArr.push(modifyLeaseDisburseBase({
                ...this.formData,
                businessTypeKey: Number(this.formData.businessTypeKey),
                businessTypeValue: this.formData.businessTypeValue,
                totalFreight: this.TotalSettlementAmountService,
                cumulativeSettlementAmount: this.setTotalSettlementAmount
            }))
            // 租赁结算明细
            // 租赁结算明细必填验证
            if(str == 'commit') {
                this.errorParmesList = []
                const errList = this.verificationSettlementDetails()
                if(errList.length > 0) {
                    this.errorParmesList = errList
                    this.setError('zljsDetail')
                    this.scorllError()
                    return
                }
            }
            //验证是否勾选退场费用
            if(str == 'commit' && this.formData.isExit) {
                if(this.tableDataExit[0].children.length == 0) {
                    this.$message.error('勾选了退场费用则必须引入退场结算明细')
                    this.setError('tcjsDetail')
                    this.scorllError()
                    return
                }
            }
            //判断合同是否在审核中
            if(str == 'commit') {
                const isType = await checkIsChange({ sourceId: this.formData.sourceId, type: String(this.formData.businessTypeKey) })
                if(isType.code && isType.code == 500) {
                    return
                }
            }
            this.detailsList[0].children.forEach(item=>{
                //changeType == 0 说明是已存在数据进行修改
                if(!item.changeType) {
                    item.changeType = 2
                }
            })
            promiseArr.push(modifyLeaseDisburseDetailLs(this.detailsList))
            // 服务费用
            promiseArr.push(modifyLeaseDisburseServiceLs(this.tableDataService))
            // 退场结算明细
            promiseArr.push(modifyLeaseDisburseZltcLs(this.tableDataExit))
            // 保证金
            this.tableDataBzj.forEach(item => {
                // 暂扣保证金
                if (item.depositType === 1) {
                    item.amountSqm = item.amount + item.amountBqm
                } else {
                    // 返还保证金
                    item.amountSqm = item.amountBqm - item.amount
                }
            })
            promiseArr.push(modifyLeaseDisburseBzjLs(this.tableDataBzj))
            // 分包商分摊成本
            this.tableDataFbsftcb.forEach(item => {
                if (item.contractType === 3) {
                    item.providType = '销售消耗'
                    item.consumeType = '销售消耗'
                }
            })
            this.tableDataFbsftcb.forEach(item=>{
                item.changeType = item.changeType || 2
            })
            promiseArr.push(modifyLeaseDisburseFtcbLs(this.tableDataFbsftcb))
            await Promise.all(promiseArr)
            if (str !== 'commit') {
                this.clientPop('suc', '保存成功', () => {
                })
                location.reload()
            } else {
                await flowCommit(this.flowParams)
                this.clientPop('suc', '操作成功', () => {
                    this.$router.replace('/turnoverLeaseDisburse')
                })
            }
        },
        //保存按钮
        onSave (str) {
            // this.$refs['ruleForm'].validate(valid => {
            //     if (valid) {
            //         this.saveFn(str)
            //     }
            // })
            this.saveFn(str)
            // this.saveFn(str, 1)
        },
        // 底部删除按钮
        onDel () {
            this.clientPop('err', this.oneDeleteErr, async () => {
                await delLeaseDisburseBase({ billId: this.billId })
                this.clientPop('suc', '操作成功', () => {
                    this.$router.replace('/turnoverLeaseDisburse')
                })
            })
        },
        async onUndo () {
            try {
                await flowUndoAudit(this.flowParams)
                this.clientPop('suc', '撤回成功', () => {
                    this.$router.replace('/turnoverLeaseDisburse')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        onNullify () {
            try {
                openAppClient('/nullifyDialog', '填写作废说明', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    await flownullify({
                        'billId': this.billId,
                        'billType': this.billType,
                        'nullifyCreated': '',
                        'nullifyCreator': '',
                        'nullifyCreatorId': '',
                        'nullifyDescription': auditParams.nullifyDescription,
                        'nullifyReason': auditParams.nullifyReason
                    })
                    this.clientPop('suc', '伤废成功', () => {
                        this.$router.replace('/turnoverLeaseDisburse')
                    })
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        //取消按钮
        onCancel () {
            if (oldRouter.path === '/turnoverLeaseDisburse') {
                this.$router.back()
            } else {
                this.$router.replace('/turnoverLeaseDisburse')
            }
        },
        exas (str) {
            switch (str) {
            case 'submit':
                this.onSave()
                break
            case 'submitCommit':
                this.onSave('commit')
                break
            case 'deleteData':
                this.onDel()
                break
            case 'undoAudit':
                this.onUndo()
                break
            case 'nullify':
                this.onNullify()
            }
        },
        getState (state) {
            const findObj = this.equipData.state.find(item => item.value === Number(state))
            return findObj ? findObj.label : ''
        },
        // 获取结算类型
        getSettlementType (state) {
            const findObj = this.turnoverData.settlementTypeArr.find(item => item.id === Number(state))
            return findObj ? findObj.name : ''
        },
        getEas (eas) {
            const findObj = this.equipData.shareFrom.find(item => item.value === eas)
            return findObj ? findObj.label : ''
        },
        showDate (date) {
            return formatDate(date, 'yyyy-MM-dd')
        },
        //租赁退场删除明细
        deleteExit (row) {
            this.tableDataExit[0].children.forEach((item, index)=>{
                if(item.sourceDtlId == row.sourceDtlId) {
                    this.clientPop(
                        'info',
                        '是否删除数据？',
                        ()=>{
                            //如果当前选中的是新增数据只需要把从数组中删除即可
                            if(row.changeType != 1) {
                                const copy = JSON.parse(JSON.stringify(this.tableDataExit[0].children[index]))
                                copy.changeType = -1
                                const paramList = [
                                    {
                                        'children': [copy],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                    }
                                ]
                                modifyLeaseDisburseZltcLs(paramList)
                            }
                            this.tableDataExit[0].children.splice(index, 1)
                            if(this.tableDataExit[0].children.length == 0) {
                                this.tableDataExit = [
                                    {
                                        'children': [],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                        'uuid': getUuid()
                                    }
                                ]
                            }
                            return
                        }
                    )
                }
            })
        },
        // 删除明细
        deleteEle (row) {
            this.detailsList[0].children.forEach((item, index)=>{
                if(item.sourceDtlId == row.sourceDtlId) {
                    this.clientPop(
                        'info',
                        '是否删除数据？',
                        ()=>{
                            //如果当前选中的是新增数据只需要把从数组中删除即可
                            if(row.changeType != 1) {
                                const copy = JSON.parse(JSON.stringify(this.detailsList[0].children[index]))
                                copy.changeType = -1
                                const paramList = [
                                    {
                                        'children': [copy],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                    }
                                ]
                                modifyLeaseDisburseDetailLs(paramList)
                            }
                            this.detailsList[0].children.splice(index, 1)
                            if(this.detailsList[0].children.length == 0) {
                                this.detailsList = [
                                    {
                                        'children': [],
                                        'topClassId': '',
                                        'topClassName': '',
                                        'totalAmount': 0,
                                        'totalQuantity': 0,
                                        'uuid': getUuid()
                                    }
                                ]
                            }
                            return
                        }
                    )
                }
            })
        },
        //将树处理为后端需要的一维数组
        flatTree (tree, list = []) {
            tree.forEach(item=>{
                const children = item.children
                delete item.children
                list.push(item)
                children && this.flatTree(children, list)
            })
            return list
        },
        // 删除暂扣保证金、返还保证金
        deleteEleBzj (row) {
            if (row.changeType === 1) {
                const index = this.tableDataBzj.find(item => item.id === row.id)
                this.tableDataBzj.splice(index, 1)
            } else {
                row.changeType = -1
            }
        },
        // 删除分包商分摊成本
        deleteEleFbsftcb (row) {
            if (row.changeType === 1) {
                const index = this.tableDataFbsftcb.find(item => item.id === row.id)
                this.tableDataFbsftcb.splice(index, 1)
            } else {
                row.changeType = -1
            }
        },
        // 查看源单
        viewYuanDan (sourceId) {
            const target = this.formData.businessTypeKey ? String(this.formData.businessTypeKey) : ''
            switch (target) {
            case '3': // 周材租赁合同
                openAppClient(`/ctRevolvMaterialApplyShow?billid=${sourceId}&isview=true`, '查看周材租赁合同')
                break
            case '5': // 临时需用计划（租赁）
                openAppClient(`/momentNeedPlanShow?billid=${sourceId}&isview=true`, '查看临时需用计划')
                break
            case '4': // 周材内租调动
                openAppClient(`/revolveInternalLeaseTransferShow?billid=${sourceId}&isview=true`, '查看周材内租调动')
                break
            }
        },
        // 修改租赁结算明细 租赁金额
        onChangeAmount (row) {
            //更新租赁时间
            if(row.leaseAmount && row.settledQuantity) {
                //数量*单价
                const returnNumber = ((Number(row.settledQuantity) || 0) * (Number(row.leasePrice) || 0))
                row.leaseTime = (row.leaseAmount / returnNumber).toFixed(2) * 1
            }else {
                row.leaseTime = 0
            }
            //判断是否超入库时间
            if(row.leaseTime > row.useTime) {
                this.$message.error('租赁时间不能超过入库时间')
                row.leaseTime = 0
            }
            //更新基本信息中的税额
            const total = this.detailsList[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
            this.formData.taxAmount = (total * (Number(this.formData.taxRate) || 0) / 100).toFixed(2)
        },
        // 修改租赁结算明细 结算数量
        settledQuantityEvent (row) {
            //验证本期结算数量是否超未结算数量
            if(row.settledQuantity > row.unsettledQuantity) {
                this.$message.error('本期结算数量不能超未结算数量')
                row.settledQuantity = row.unsettledQuantity || 0
            }
            //更新租赁时间
            if(row.leaseAmount && row.settledQuantity) {
                row.leaseTime = (row.leaseAmount / row.settledQuantity * (row.leasePrice || 0)).toFixed(2) * 1
            }else {
                row.leaseTime = 0
            }
            //判断是否超入库时间
            if(row.leaseTime > row.useTime) {
                this.$message.error('租赁时间不能超过入库时间')
                row.leaseTime = 0
            }
        },
        // 选择物资 租赁结算明细
        onSelectMaterial () {
            selectDataClient({
                SelectServiceToken: '/turnover/warehousing/SelectLeaseExpendSettleDtl',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    parentId: '0',
                    businessType: this.formData.businessTypeKey
                }),
                Title: '选择结算明细' // 标题
            }).then(val => {
                if(val.length > 0) {
                    //除去父级
                    const father = val.filter(item=>item.parentId == '0')
                    const target = val.filter(item=>item.parentId != '0')
                    this.setAcceptanceDataTable(target)
                    const resData = target[0]
                    this.formData.settlementUnitId = resData.settleOrgId || (father[0] ? father[0].settleOrgId : '')
                    this.formData.settlementUnitName = resData.settleOrgName || (father[0] ? father[0].settleOrgName : '')
                    this.formData.sourceId = resData.sourceId
                    this.formData.sourceNo = resData.sourceNo
                    this.formData.taxRate = resData.taxRate || 0
                    //获取清单截止上期末累计结算金额
                    getPrevAmount({ sourceId: resData.sourceId })
                        .then(res=>{
                            if(typeof res == 'number') {
                                this.previousTotalAmount = res
                            }else {
                                this.previousTotalAmount = 0
                            }
                        })
                    this.iSiTrequiredAdd ( this.formData.settlementUnitId, this.formData.settlementUnitName)
                }
            }).catch(err => {
                alert(err.message)
            })
        },
        //查看冲销对象中是否有当前新增数据
        iSiTrequiredAdd (targetId, targetName) {
            const list = this.reversalObjectList
            //是否需要新增 false 不要 ture 要
            let isAdd = true
            for (const key in list) {
                //已存在直接退出
                if(list[key].reversalObjectId == targetId) {
                    isAdd = false
                    break
                }
            }
            if(isAdd) {
                const obj = {
                    reversalObjectId: targetId || '',
                    reversalObjectName: targetName || ''
                }
                this.reversalObjectList.push(obj)
            }
        },
        //设置表格
        setAcceptanceDataTable (list = []) {
            const subjectList =  this.detailsList[0].children
            const subLength = subjectList.length
            const length = list.length
            const targetList = []
            for (let i = 0; i < length; i++) {
                let isRepeat = false
                for (let j = 0; j < subLength; j++) {
                    if(list[i].dtlId == subjectList[j].sourceDtlId) {
                        isRepeat = true
                        break
                    }
                }
                //没有就新增
                if(!isRepeat) {
                    const item = list[i]
                    const obj = {
                        'billId': this.billId,
                        'changeType': 1,
                        'dtlId': '',
                        'endTime': '',
                        'leaseAmount': 0,
                        'leasePrice': item.sourcePrice,
                        'leaseTime': 0,
                        'materialClassId': item.materialClassId,
                        'materialClassName': item.materialClassName,
                        'materialId': item.materialId,
                        'materialName': item.materialName,
                        'settledQuantity': item.notSettleQuantity, //默认为未结算数量
                        'sourceDtlId': item.dtlId,
                        'spec': item.spec,
                        'startTime': '',
                        'texture': item.texture,
                        'timingUnit': item.timeUnit,
                        'unit': item.unit,
                        'unsettledQuantity': item.notSettleQuantity,
                        'useTime': item.useTime,
                        'warehouseId': item.warehouseId,
                        'warehouseName': item.warehouseName,
                        'uuid': getUuid()
                    }
                    targetList.push(obj)
                }
            }
            this.detailsList[0].children.push(...targetList)
        },
        //冲销对象事件
        changeReversalObject (val) {
            this.formData.reversalObjectId = val
            let obj = {}
            obj = this.reversalObjectList.find(item=>{
                return item.reversalObjectId === val
            })
            this.formData.reversalObjectName = obj.reversalObjectName
        },
        // 新增按钮 服务费用
        async onAddList1 () {
            this.tableDataService.push({
                id: getUuid(),
                'amount': 0,
                'billId': this.billId,
                'changeType': 1,
                'contractBillId': '',
                'contractDtlName': '',
                'contractId': '',
                'contractNumber': '',
                'dtlId': '',
                'invoiceNo': '',
                'price': 0,
                'quantity': 0,
                'settlementUnitId': '',
                'settlementUnitName': '',
                'taxAmount': 0,
                'taxRate': 0,
                'totalAmount': 0
            })
        },
        // 删除服务费用
        deleteEleService (row) {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                () => {
                    //新增直接从数组中删除
                    if(row.changeType == 1) {
                        this.tableDataService = this.tableDataService.filter(item=>item.id != row.id)
                    }else {
                        const target = this.tableDataService.filter(item=>item.dtlId == row.dtlId)
                        this.tableDataService = this.tableDataService.filter(item=>item.dtlId != row.dtlId)
                        target[0].changeType = -1
                        modifyLeaseDisburseServiceLs(target)
                    }
                    //删除冲销对象中的单位
                    const target = this.reversalObjectList
                    for (const key in target) {
                        if(target[key].reversalObjectId == row.settlementUnitId) {
                            this.reversalObjectList.splice(key, 1)
                            if(this.formData.reversalObjectName == row.settlementUnitName) {
                                this.formData.reversalObjectName = ''
                            }
                            break
                        }
                    }
                }
            )
        },
        // 服务费用 选择物资采购合同
        async onSelectHetong (index) {
            // 物资验收-服务费用弹框:选择合同
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getLeaseAcceptanceSettlementContract', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
                InitParamsStr: '',    // 接口参数(name为模拟参数)
                Title: '选择合同' // 标题
            })
                .then(data=>{
                    const res = data[0]
                    let result
                    // 如果选择的是合同并且合同下有清单,则需带入合同下的清单
                    if (res.list && res.list.length > 0) {
                        result = res.list.map(item => {
                            return {
                                amount: null,
                                billId: this.billId,
                                changeType: 1,
                                contractId: res.contractId,
                                contractNumber: res.contractNumber,
                                contractDtlId: item.detailedId,
                                contractDtlName: item.name,
                                contractQuantity: item.quantity, // 这个字段是用于在修改数量时,不能大于合同数量的
                                dtlId: '',
                                invoiceNo: '',
                                price: null,
                                quantity: item.quantity,
                                settlementUnitId: res.secondPartyId,
                                settlementUnitName: res.secondPartyName,
                                taxAmount: 0,
                                taxRate: res.taxRate,
                                totalAmount: 0,
                            }
                        })
                        let _arr = []
                        result.forEach(item => {
                            const shouldPush = this.tableDataService.every(
                                it => item.contractDtlId !== it.contractDtlId
                            )
                            if (shouldPush) {
                                _arr.push(item)
                            } else {
                                // 找到了清单ID相同
                                const repeatArr = this.tableDataService.filter(
                                    i => item.contractDtlId === i.contractDtlId
                                )
                                const noPush = repeatArr.some(
                                    _its => _its.changeType !== -1
                                )
                                if (!noPush) {
                                    _arr.push(item)
                                }
                            }
                        })
                        if (_arr.length !== 0) {
                            this.tableDataService.splice(index, 1, ..._arr)
                        }
                    } else {
                        // 如果选择的合同没有清单
                        result = {
                            amount: null,
                            billId: this.billId,
                            changeType: 1,
                            contractBillId: res.contractId,
                            contractBillNo: res.contractNumber,
                            contractBillType: res.contractType,
                            dtlId: '',
                            invoiceNo: '',
                            price: null,
                            quantity: null,
                            settlementUnitId: res.secondPartyId,
                            settlementUnitName: res.secondPartyName,
                            taxAmount: 0,
                            taxRate: res.taxRate,
                            totalAmount: 0,
                            contractDtlId: '',
                            contractDtlName: '',
                            contractId: res.contractId,
                            contractNumber: res.contractNumber,
                        }
                        const shouldPush = this.tableDataService.every(
                            it => it.contractBillId !== result.contractBillId
                        )
                        if (shouldPush) {
                            this.tableDataService.splice(index, 1, result)
                        } else {
                            const repeatArr = this.tableDataService.filter(
                                i => i.contractBillId === result.contractBillId
                            )
                            const noPush = repeatArr.some(
                                _its => _its.changeType !== -1
                            )
                            if (!noPush) {
                                this.tableDataService.splice(index, 1, result)
                            }
                        }
                    }
                })

        },
        // 服务费用 选择结算单位
        onSelectJsUnit (row) {
            selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [row.settlementUnitId], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[]) // 这个是客户端给的,没有则为空
                InitParamsStr: JSON.stringify(this.jsdwData), // 接口参数(name为模拟参数)
                Title: '选择结算单位' // 标题
            }).then(val => {
                row.settlementUnitId = val[0].outerId
                row.settlementUnitName = val[0].outerName
            })
        },
        //服务费用 清单名称
        detailedListNameBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        //服务费用 发票编号
        invoiceNoBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
        },
        //服务费用 数量
        quantityBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            // // 不能超过合同数量
            if (row.contractQuantity) {
                if (row.quantity > row.contractQuantity) {
                    this.clientPop(
                        'err',
                        `不能超过合同数量${row.contractQuantity}`
                    )
                    row.quantity = row.contractQuantity
                }
            }
            if (+row.amount && +row.quantity) {
                row.price = (row.amount / row.quantity).toFixed(2) * 1
            }else {
                row.price = 0
            }
        },
        //服务费用 金额
        amountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算单价
            if (+row.amount && +row.quantity) {
                row.price = (+row.amount / +row.quantity).toFixed(2) * 1
            }else {
                row.price = 0
            }
            //计算税额
            row.taxAmount = ((Number(row.amount) || 0) * (row.taxRate ? row.taxRate / 100 : 0)).toFixed(2) * 1
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        //服务费用 税率
        taxRateBlur (row) {
            if(row.taxRate > 100 || row.taxRate < 0) {
                row.taxRate = 0
                this.$message.error('税率有效范围为0~100')
            }
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算税额
            row.taxAmount = ((Number(row.amount) || 0) * (row.taxRate ? row.taxRate / 100 : 0)).toFixed(2) * 1
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        //服务费用 税额
        taxAmountBlur (row) {
            if (row.changeType == 1) {
                row.changeType = 1
            } else {
                row.changeType = 2
            }
            //计算税价合计
            row.totalAmount = ((Number(row.amount) || 0) + (Number(row.taxAmount) || 0)).toFixed(2) * 1
        },
        // 选择借支人员
        onGetSigningName () {
            selectDataClient({
                SelectServiceToken: '/hr/user/getUserUnderOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({ 'orgId': this.formData.orgId }),    // 接口参数
                Title: '选择借支人员' // 标题
            }).then(val => {
                const res = val[0]
                this.formData.borrowerId = res.userId
                this.formData.borrowerName = res.userName
            })
        },
        // 选择周材租赁退场结算明细
        onSelectExitDetail () {
            selectDataClient({
                SelectServiceToken: '/turnover/leaseExit/getLeaseExitDtl', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify(this.formData.settlementUnitId), // 接口参数
                Title: '选择租赁退场明细' // 标题
            }).then(val => {
                // 验证本次选中数据是否已存在
                const oldList = this.tableDataExit[0].children
                const oldLength = oldList.length
                const valLength = val.length
                const targetList = []
                for (let i = 0; i < valLength; i++) {
                    let isRepeat = false
                    for (let j = 0; j < oldLength; j++) {
                        //找到说明有重复
                        if(val[i].dtlId == oldList[j].sourceDtlId) {
                            isRepeat = true
                            break
                        }
                    }

                    //没有就新增
                    if(!isRepeat) {
                        const item = val[i]
                        item.sourceDtlId = item.dtlId //周材租赁退场明细id
                        item.dtlId = '' // 退场明细id
                        item.billId = this.billId // 周材租赁支出结算id
                        item.changeType = 1 // 新增
                        item.uuid = getUuid() // 表格需要id
                        item.receiptQuantity = item.warehousingQuantity //入库数量
                        item.exitsQuantitySqm = item.prevTotalReturnQuantity || 0 //截止上期末退场数量
                        item.exitsQuantityBqm = item.currTotalReturnQuantity || 0 //截止本期末退场数量
                        item.exitsQuantity = ((Number(item.exitsQuantityBqm) || 0) - (Number(item.exitsQuantitySqm) || 0)).toFixed(4) * 1 //本期退场数量
                        item.exitsTime = item.returnTime //退场时间
                        item.reason = item.lossReason //退场时间
                        targetList.push(item)
                    }
                }
                this.tableDataExit[0].children.push(...targetList)

            })
        },
        // 选择暂扣保证金
        onAddListZk () {
            selectDataClient({
                SelectServiceToken: '/turnoversettle/Api/getWithholdDeposit',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: this.billType,
                Title: '选择暂扣保证金' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果')
                // const val = [{ 'deductionRatio': 0.05, 'depositId': '1523870830363680770', 'depositName': '其他保证金', 'prevTotalAmount': null }, { 'deductionRatio': 0.05, 'depositId': '1523870830116216833', 'depositName': '安全保证金', 'prevTotalAmount': null }, { 'deductionRatio': 0.05, 'depositId': '1523870830267211777', 'depositName': '民工工资保证金', 'prevTotalAmount': null }, { 'deductionRatio': 0.05, 'depositId': '1523870829990387714', 'depositName': '质量保证金', 'prevTotalAmount': null }]
                const tableDataBzj = val.map(item => ({
                    id: item.dtlId,
                    'amount': 0,
                    'amountBqm': item.prevTotalAmount,
                    'amountSqm': 0,
                    'billId': this.billId,
                    'changeType': 1,
                    'depositType': 1,
                    'dtlId': '',
                    'remarks': '',
                    'returnDepositId': item.depositId,
                    'returnDepositName': item.depositName
                }))
                this.tableDataBzj.push(...tableDataBzj)
            })
        },
        // 选择返还保证金
        onAddListFh () {
            selectDataClient({
                SelectServiceToken: '/turnoversettle/Api/getReturnDeposit',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    'billType': this.billType,
                    'sourceId': this.formData.sourceId
                }),
                Title: '选择返还保证金' // 标题
            }).then(val => {
                const tableDataBzj = val.forEach(item => ({
                    id: item.dtlId,
                    'amount': 0,
                    'amountBqm': item.notReturnDepositAmount,
                    'amountSqm': 0,
                    'billId': this.billId,
                    'changeType': 1,
                    'depositType': 2,
                    'dtlId': '',
                    'remarks': '',
                    'returnDepositId': item.returnDepositId,
                    'returnDepositName': item.returnDepositName
                }))
                this.tableDataBzj.push(...tableDataBzj)
            })
        },
        // 选择分包商
        onSelectFbsftcb () {
            selectDataClient({
                SelectServiceToken: '/turnover/receive/returnSelectContract', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: '-1',    // 接口参数
                Title: '选择分包商' // 标题
            }).then(val => {
                const arr = val.map(item => ({
                    id: item.contractId,
                    'apportionmentAmount': 0,
                    'apportionmentRatio': 0,
                    'billId': this.billId,
                    'changeType': 1,
                    'consumeType': 0,
                    'dtlId': '',
                    'planAmount': item.contractAmount,
                    'providType': 1,
                    contractType: item.contractType,
                    'subcontractId': item.contractId,
                    'subcontractName': item.contractName,
                    'subcontractNumber': item.contractNumber,
                    'subcontractorId': item.secondPartyId,
                    'subcontractorName': item.secondPartyName
                }))
                // 剔重已有的
                const arr2 = arr.filter(item => {
                    const findObj = this.tableDataFbsftcb.find(subItem => subItem.subcontractId === item.subcontractId)
                    // 没有的才添加
                    return !findObj
                })
                this.tableDataFbsftcb = this.tableDataFbsftcb.concat(arr2)
            })
        },
        // 迭代树，找出 changeType !== -1 的数据
        showData (data) {
            const result = []
            let stack = this._.clone(data)
            let item = stack.shift()
            const mapObj = {}
            // 迭代树，找出 changeType !== -1 的数据
            while (item) {
                if (!item.id) {
                    item.id = item.dtlId
                }
                mapObj[item.id] = item
                if (item.parentId === '0') {
                    if (item.changeType !== -1) {
                        result.push(item)
                    }
                } else if (item.changeType === -1) {
                    // children 中有 changeType === -1 时则删掉
                    let i = 0
                    const clds = mapObj[item.parentId].children
                    let cld = clds[i]
                    while (cld) {
                        if (cld.id === item.id) {
                            clds.splice(i, 1)
                            break
                        }
                        cld = clds[++i]
                    }
                }
                if (item.children && item.children.length) {
                    stack = stack.concat(item.children)
                }
                item = stack.shift()
            }
            // 显示 changeType !== -1 的数据
            return result
        },
        //切换业务类型事件
        onSelectBusinessTypeKey (val) {
            this.detailsList = [
                {
                    'children': [],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': getUuid()
                }
            ]
            //业务类型
            const type = {
                '3': '周材租赁合同',
                '4': '周材内租调动',
                '5': '临时需用计划'
            }
            this.formData.businessTypeKey = Number(val)
            this.formData.businessTypeValue = type[val]
            this.formData.settlementUnitName = ''
            this.formData.settlementType = val == '4' ? 1 : 2
            this.formData.sourceId = ''
            if(val != '5') {
                this.formData.isPersonalBorrowing = false
                this.formData.reversalObjectName = ''
                this.formData.reversalObjectId = ''
                this.formData.borrowerName = ''
                this.formData.personalBorrowing = 0
            }
        },
        async clickIcon (row) {
            console.log('clickIcon: ', row)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        setErrortMsg (msg) {
            let index = this.errorMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorMsg.push(msg)
            }
        },
        clearErrorMsg () {
            this.errorMsg = []
            this.errorMsg2 = []
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        registScroll () {
            window.removeEventListener('scroll', this.winEvent.onScroll)
            window.removeEventListener('resize', this.winEvent.onResize)

            // 保存所有tabName
            let arr = ['baseInfo', 'zljsDetail', 'serviceFy', 'tcjsDetail', 'bzj', 'fbsftcb', 'attach', 'auditHistory']
            let $idsTop = []
            const onScroll = () => {
                // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
                if (this.clickTabFlag) {
                    return
                }
                if (!$idsTop[$idsTop.length - 1]) {
                    $idsTop = arr.map(item => {
                        const $item = document.getElementById(item)
                        let itemTop = null
                        if ($item) {
                            itemTop = $item.offsetTop
                        }
                        return itemTop
                    })
                }
                const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
                // 倒序查找
                let curLocal = 0
                for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
                // 设置对应tabName
                this.tabsName = arr[curLocal]
            }
            this.winEvent.onScroll = throttle(onScroll, 100)
            window.addEventListener('scroll', this.winEvent.onScroll)
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            const onResize = () => {
                this.screenWidth = document.documentElement.clientWidth
                this.screenHeight = document.documentElement.clientHeight
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            this.winEvent.onResize = throttle(onResize, 500)
            window.addEventListener('resize', this.winEvent.onResize)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //分包商分摊金额事件用于计算分摊比例
        apportionmentAmountEvent () {
            const total = this.tableDataFbsftcbShow.reduce((a, b)=>a + Number(b.apportionmentAmount) || 0, 0)
            this.tableDataFbsftcbShow.forEach(item=>{
                item.apportionmentAmount = Number(item.apportionmentAmount)
                item.apportionmentRatio = (item.apportionmentAmount / total).toFixed(2) * 100
            })
            if(total != this.formData.taxExcluding) {
                this.$message.error(`分摊金额总计必须等于基本信息中不含税金额。当前不含税金额：为${this.formData.taxExcluding},分摊金额总计为${total}`)
            }
        },
        //进场费事件
        slottingFeeEvent (val) {
            //计算不含税金额
            const total = this.detailsList[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
            this.formData.taxExcluding = (total + (Number(this.formData.damages) || 0) + (Number(val) || 0) + (Number(this.formData.exitFees) || 0)).toFixed(2) * 1
            //计算税价合计
            this.formData.totalAmount = ((Number(this.formData.taxExcluding) || 0) +
            (Number(this.formData.taxAmount ) || 0)).toFixed(2) * 1
        },
        //退场费事件
        exitFeesEvent (val) {
            //计算不含税金额
            const total = this.detailsList[0].children.reduce((a, b)=>a + Number(b.leaseAmount), 0)
            this.formData.taxExcluding = total + (Number(this.formData.damages) || 0) + (Number(this.formData.slottingFee) || 0) + (Number(val) || 0)
            //计算税价合计
            this.formData.totalAmount = (Number(this.formData.taxExcluding) || 0) +
            (Number(this.formData.taxAmount ) || 0)
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
.e-table {
    background: #fff;
}
.el-tab-pane {
    margin-left: -10px;
}
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
::v-deep.el-table__row{
    .cell{
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
.errMessage {
    color: red;
    font-size: 14px;
}
</style>
